package com.jxb.myshop.services.impl;

import com.jxb.myshop.common.Constant;
import com.jxb.myshop.common.ResponseResult;
import com.jxb.myshop.dao.AddressDao;
import com.jxb.myshop.dao.impl.AddressDaoImpl;
import com.jxb.myshop.entity.Address;
import com.jxb.myshop.services.AddressServices;

import java.sql.SQLException;
import java.util.List;

public class AddressServicesImpl implements AddressServices {
    private AddressDao ad = new AddressDaoImpl();

    @Override
    public ResponseResult getUserAddress(int uid) {
        try {
            List<Address> addList =  ad.getUserAddress(uid);
            if (addList != null && addList.size() != 0) {
                return ResponseResult.createSuccess(addList);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ResponseResult.createFail("获取地址失败");
    }

    @Override
    public ResponseResult addAddress(Address add) {
        try {
            add.setAstate(Constant.User.NOT_DEFAULT_ADDRESS);
            int i = ad.addAddress(add);
            if (i > 0){
                return ResponseResult.createSuccess("地址添加成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.createFail("地址添加失败");
    }

    @Override
    public ResponseResult deleteAddress(int aid) {
        try {
            if (aid > 0) {
                if (ad.deleteAddress(aid) > 0) {
                    return ResponseResult.createSuccess("删除成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.createFail("删除失败");
    }

    @Override
    public ResponseResult updateAddress(Address a)  {
        try {
            if (ad.updateAddress(a) > 0) {
                return ResponseResult.createSuccess("修改成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ResponseResult.createFail("修改失败");
    }

    @Override
    public ResponseResult updateAddressDefault(int aid,int uid) {
        try {
            // 因为默认地址是1，而且默认地址只有一个，所以当修改默认地址应该先把其他的设置为0，再把它设置为1
            ad.setAddressNotDefault(uid);
            int i = ad.setAddressDefault(aid);
            if (i > 0){
                return ResponseResult.createSuccess("修改成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.createFail("修改失败");
    }
}
